package com.lijiajia.cloud.resource.sys.config.security.resourceserver;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 资源服务器 配置
 *
 * @author lijiajia
 * @since 2019-05-28
 */
@EnableResourceServer
@Configuration
@Order(90)
public class ResourceServerConfigurer implements org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurer {
    private final ResourceServerProperties resource;
    private final TokenStore tokenStore;
    private final AuthenticationEventPublisher eventPublisher;
    private final ExpressionUrlAuthorizationConfigurer<HttpSecurity> expressionUrlAuthorizationConfigurer;

    public ResourceServerConfigurer(ResourceServerProperties resource,
                                    @Qualifier("jwtTokenStore") TokenStore tokenStore,
                                    AuthenticationEventPublisher eventPublisher,
                                    ExpressionUrlAuthorizationConfigurer<HttpSecurity> expressionUrlAuthorizationConfigurer) {
        this.resource = resource;
        this.eventPublisher = eventPublisher;
        this.tokenStore = tokenStore;
        this.expressionUrlAuthorizationConfigurer = expressionUrlAuthorizationConfigurer;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

        resources.resourceId(resource.getResourceId())
                .tokenStore(tokenStore)
                .eventPublisher(eventPublisher);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.apply(expressionUrlAuthorizationConfigurer);
    }
}
